<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="hover" class="search-card mb-4">
      <div class="search-header flex justify-between items-center mb-3">
        <h3 class="text-lg font-semibold">查询条件</h3>
        <el-button
            icon="Filter"
            size="small"
            @click="toggleAdvancedSearch"
            type="text"
            class="search-toggle-btn"
        >
          {{ showAdvancedSearch ? '收起高级搜索' : '展开高级搜索' }}
        </el-button>
      </div>

      <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="100px"
          size="small"
      >
        <!-- 基础搜索项 -->
        <el-row :gutter="20" class="mb-2">
          <el-col :span="5">
            <el-form-item label="学生学号" prop="studentId">
              <el-input
                  v-model="queryParams.studentId"
                  placeholder="请输入学生学号"
                  clearable
                  @keyup.enter="handleQuery"
                  class="form-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="学生姓名" prop="studentName">
              <el-input
                  v-model="queryParams.studentName"
                  placeholder="请输入学生姓名"
                  clearable
                  @keyup.enter="handleQuery"
                  class="form-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="学院名称" prop="collegeName">
              <el-input
                  v-model="queryParams.collegeName"
                  placeholder="请输入学院名称"
                  clearable
                  @keyup.enter="handleQuery"
                  class="form-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="专业名称" prop="majorName">
              <el-input
                  v-model="queryParams.majorName"
                  placeholder="请输入专业名称"
                  clearable
                  @keyup.enter="handleQuery"
                  class="form-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4" class="flex items-end">
            <el-button type="primary" icon="Search" @click="handleQuery" class="mr-2">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>

        <!-- 高级搜索项 - 可折叠 -->
        <el-collapse v-model="advancedSearchCollapse" class="mt-2" border="false">
          <el-collapse-item name="advanced" title="高级搜索">
            <el-row :gutter="20" class="mb-2">
              <el-col :span="5">
                <el-form-item label="注册学期" prop="registrationSemester">
                  <el-input
                      v-model="queryParams.registrationSemester"
                      placeholder="请输入注册学期"
                      clearable
                      @keyup.enter="handleQuery"
                      class="form-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="注册时间" prop="registrationTime">
                  <el-date-picker clearable
                                  v-model="queryParams.registrationTime"
                                  type="date"
                                  value-format="YYYY-MM-DD"
                                  placeholder="请选择注册时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="注册IP地址" prop="registrationIp">
                  <el-input
                      v-model="queryParams.registrationIp"
                      placeholder="请输入注册IP地址"
                      clearable
                      @keyup.enter="handleQuery"
                      class="form-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="注册状态" prop="registrationStatus">
                  <el-select
                      v-model="queryParams.registrationStatus"
                      placeholder="请选择注册状态"
                      clearable
                      class="form-select"
                  >
                    <el-option label="待审核" value="0"></el-option>
                    <el-option label="已通过" value="1"></el-option>
                    <el-option label="已驳回" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20" class="mb-2">
              <el-col :span="5">
                <el-form-item label="审核人ID" prop="auditUserId">
                  <el-input
                      v-model="queryParams.auditUserId"
                      placeholder="请输入审核人ID"
                      clearable
                      @keyup.enter="handleQuery"
                      class="form-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="审核时间" prop="auditTime">
                  <el-date-picker clearable
                                  v-model="queryParams.auditTime"
                                  type="date"
                                  value-format="YYYY-MM-DD"
                                  placeholder="请选择审核时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="创建人" prop="createBy">
                  <el-input
                      v-model="queryParams.createBy"
                      placeholder="请输入创建人"
                      clearable
                      @keyup.enter="handleQuery"
                      class="form-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="创建时间" prop="createTime">
                  <el-date-picker clearable
                                  v-model="queryParams.createTime"
                                  type="date"
                                  value-format="YYYY-MM-DD"
                                  placeholder="请选择创建时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20" class="mb-2">
              <el-col :span="5">
                <el-form-item label="更新人" prop="updateBy">
                  <el-input
                      v-model="queryParams.updateBy"
                      placeholder="请输入更新人"
                      clearable
                      @keyup.enter="handleQuery"
                      class="form-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="更新时间" prop="updateTime">
                  <el-date-picker clearable
                                  v-model="queryParams.updateTime"
                                  type="date"
                                  value-format="YYYY-MM-DD"
                                  placeholder="请选择更新时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="浏览器信息" prop="browserInfo">
                  <el-input
                      v-model="queryParams.browserInfo"
                      placeholder="请输入浏览器信息"
                      clearable
                      @keyup.enter="handleQuery"
                      class="form-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="操作系统" prop="osInfo">
                  <el-input
                      v-model="queryParams.osInfo"
                      placeholder="请输入操作系统"
                      clearable
                      @keyup.enter="handleQuery"
                      class="form-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="operation-bar-flex">
      <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['student:registration:add']"
          size="small"
          class="operation-btn"
      >新增</el-button>
      <el-button
          type="success"
          icon="Edit"
          :disabled="!single"
          @click="handleUpdate"
          v-hasPermi="['student:registration:edit']"
          size="small"
          class="operation-btn"
      >修改</el-button>
      <el-button
          type="danger"
          icon="Delete"
          :disabled="!multiple"
          @click="handleDelete"
          v-hasPermi="['student:registration:remove']"
          size="small"
          class="operation-btn"
      >删除</el-button>
      <el-button
          type="warning"
          icon="Download"
          @click="handleExport"
          v-hasPermi="['student:registration:export']"
          size="small"
          class="operation-btn"
      >导出</el-button>
      <el-button
          type="success"
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['student:registration:import']"
          size="small"
          class="operation-btn"
      >导入学生信息</el-button>
      <el-button
          type="primary"
          icon="Calendar"
          @click="handleOpenSetTimeDialog"
          v-hasPermi="['student:registryTime:edit']"
          size="small"
          class="operation-btn"
      >设置注册时间</el-button>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" class="ml-auto"></right-toolbar>
    </div>

    <!-- 表格区域 -->
    <el-card shadow="hover" class="table-card">
      <div class="table-header flex justify-between items-center mb-3">
        <h3 class="text-lg font-semibold">学生注册列表</h3>
        <div class="table-count text-gray-500">
          共 <span class="text-primary font-medium">{{ total }}</span> 条记录
        </div>
      </div>

      <el-table
          v-loading="loading"
          :data="registrationList"
          @selection-change="handleSelectionChange"
          stripe
          border
          size="small"
          highlight-current-row
          :header-cell-style="{background: '#f5f7fa', fontWeight: '500'}"
          class="content-table"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="学生学号" align="center" prop="studentId" min-width="200" />
        <el-table-column label="学生姓名" align="center" prop="studentName" min-width="170" />
        <el-table-column label="学院ID" align="center" prop="collegeId" min-width="80" />
        <el-table-column label="学院名称" align="center" prop="collegeName" min-width="170" />
        <el-table-column label="专业ID" align="center" prop="majorId" min-width="80" />
        <el-table-column label="专业名称" align="center" prop="majorName" min-width="170" />
        <el-table-column label="注册学期" align="center" prop="registrationSemester" min-width="120" >
          <template #default="scope">
            {{ termList.find(item => item.termCode === scope.row.registrationSemester)?.termName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="注册时间" align="center" prop="registrationTime" min-width="120">
          <template #default="scope">
            <span>{{ scope.row.registrationTime ? parseTime(scope.row.registrationTime, '{y}-{m}-{d}') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="注册IP地址" align="center" prop="registrationIp" min-width="120" />
        <el-table-column label="浏览器信息" align="center" prop="browserInfo" min-width="120" />
        <el-table-column label="操作系统" align="center" prop="osInfo" min-width="120" />
        <el-table-column label="注册状态" align="center" prop="registrationStatus" min-width="100">
          <template #default="scope">
            <el-tag
                :type="scope.row.registrationStatus === 0 ? 'warning' :
                      scope.row.registrationStatus === 1 ? 'success' : 'info'"
                size="small"
            >
              {{ scope.row.registrationStatus === 0 ? '待审核' :
                scope.row.registrationStatus === 1 ? '已通过' : '已驳回' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核人ID" align="center" prop="auditUserId" min-width="100" />
        <el-table-column label="审核时间" align="center" prop="auditTime" min-width="120">
          <template #default="scope">
            <span>{{ scope.row.auditTime ? parseTime(scope.row.auditTime, '{y}-{m}-{d}') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核备注" align="center" prop="auditRemark" min-width="120" />
        <el-table-column label="创建人" align="center" prop="createBy" min-width="100" />
        <el-table-column label="创建时间" align="center" prop="createTime" min-width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新人" align="center" prop="updateBy" min-width="100" />
        <el-table-column label="更新时间" align="center" prop="updateTime" min-width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注信息" align="center" prop="remark" min-width="210" />
        <el-table-column label="操作" align="center" min-width="140" fixed="right">
          <template #default="scope">
            <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['student:registration:edit']"
                size="small"
                class="table-operation-btn"
            >修改</el-button>
            <el-button
                link
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['student:registration:remove']"
                size="small"
                class="table-operation-btn"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
          class="mt-4 pagination"
      />
    </el-card>

    <!-- 添加或修改学生注册对话框 -->
    <el-dialog
        :title="title"
        v-model="open"
        width="700px"
        append-to-body
        :close-on-click-modal="false"
        destroy-on-close
        class="custom-dialog"
    >
      <el-form
          ref="registrationRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          size="small"
          class="dialog-form"
      >
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="学生学号" prop="studentId">
              <el-input v-model="form.studentId" placeholder="请输入学生学号" class="form-input" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="学生姓名" prop="studentName">
              <el-input v-model="form.studentName" placeholder="请输入学生姓名" class="form-input" />
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="学院ID" prop="collegeId">
              <el-input v-model="form.collegeId" placeholder="请输入学院ID" class="form-input" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="学院名称" prop="collegeName">
              <el-input v-model="form.collegeName" placeholder="请输入学院名称" class="form-input" />
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="专业ID" prop="majorId">
              <el-input v-model="form.majorId" placeholder="请输入专业ID" class="form-input" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="专业名称" prop="majorName">
              <el-input v-model="form.majorName" placeholder="请输入专业名称" class="form-input" />
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="注册学期" prop="registrationSemester">
              <el-input v-model="form.registrationSemester" placeholder="请输入注册学期" class="form-input" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="注册时间" prop="registrationTime">
              <el-date-picker clearable
                              v-model="form.registrationTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择注册时间">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="注册IP地址" prop="registrationIp">
              <el-input v-model="form.registrationIp" placeholder="请输入注册IP地址" class="form-input" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="注册状态" prop="registrationStatus">
              <el-select
                  v-model="form.registrationStatus"
                  placeholder="请选择注册状态"
                  filterable
                  class="form-select"
              >
                <el-option label="待审核" value="0"></el-option>
                <el-option label="已通过" value="1"></el-option>
                <el-option label="已驳回" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="浏览器信息" prop="browserInfo">
              <el-input v-model="form.browserInfo" placeholder="请输入浏览器信息" class="form-input" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="操作系统" prop="osInfo">
              <el-input v-model="form.osInfo" placeholder="请输入操作系统信息" class="form-input" />
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="审核人ID" prop="auditUserId">
              <el-input v-model="form.auditUserId" placeholder="请输入审核人ID" class="form-input" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="审核时间" prop="auditTime">
              <el-date-picker clearable
                              v-model="form.auditTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择审核时间">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="22">
            <el-form-item label="审核备注" prop="auditRemark">
              <el-input v-model="form.auditRemark" type="textarea" placeholder="请输入审核备注" rows="2" class="form-textarea" />
            </el-form-item>
          </el-col>

          <el-col :span="22">
            <el-form-item label="备注信息" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" rows="2" class="form-textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel" size="small" class="dialog-btn">取 消</el-button>
          <el-button type="primary" @click="submitForm" size="small" class="dialog-btn dialog-btn-primary">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入进度对话框 -->
    <el-dialog
        title="导入进度"
        v-model="importProgressVisible"
        width="400px"
        append-to-body
        :close-on-click-modal="false"
        :show-close="false"
        class="custom-dialog"
    >
      <div class="import-progress-container">
        <div v-if="importStatus === '处理中'" class="status-info">
          <p class="text-center mb-4">正在导入学生信息，请稍候...</p>
          <el-progress
              :percentage="importProgress"
              stroke-width="6"
              :status="importProgress < 100 ? '' : 'success'">
          </el-progress>
          <div class="progress-stats mt-3 flex justify-between text-sm">
            <span>已完成: {{ importSuccessCount }} / {{ importTotalCount }}</span>
            <span>{{ importProgress }}%</span>
          </div>
        </div>

        <div v-if="importStatus === '完成'" class="status-info success-state">
          <div class="text-center">
            <el-icon class="success-icon"><Check /></el-icon>
            <p class="mt-3">导入完成！</p>
            <p class="mt-1">共导入 {{ importSuccessCount }} 条学生信息</p>
          </div>
        </div>

        <div v-if="importStatus === '失败'" class="status-info error-state">
          <div class="text-center">
            <el-icon class="error-icon"><Close /></el-icon>
            <p class="mt-3">导入失败</p>
            <p class="mt-1 error-message">{{ importErrorMsg }}</p>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button
              v-if="importStatus !== '处理中'"
              type="primary"
              @click="closeImportProgress"
              size="small"
              class="dialog-btn dialog-btn-primary"
          >
            关闭
          </el-button>
          <el-button
              v-if="importStatus === '处理中'"
              type="warning"
              @click="cancelImport"
              size="small"
              class="dialog-btn"
          >
            取消导入
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设置注册时间对话框 -->
    <el-dialog
        title="设置注册时间范围"
        v-model="setTimeDialogVisible"
        width="500px"
        append-to-body
        :close-on-click-modal="false"
        destroy-on-close
        class="custom-dialog"
    >
      <el-form
          ref="setTimeFormRef"
          :model="setTimeForm"
          :rules="setTimeRules"
          label-width="120px"
          size="small"
      >
        <!-- 开始时间（回显现有值） -->
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
              v-model="setTimeForm.startTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择开始时间"
              clearable
              :disabled="loadingTime"
          />
        </el-form-item>
        <!-- 结束时间（回显现有值） -->
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
              v-model="setTimeForm.endTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择结束时间"
              clearable
              :disabled="loadingTime"
              :disabled-date="(time) => time < new Date(setTimeForm.startTime)"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="setTimeDialogVisible = false" size="small" class="dialog-btn">取 消</el-button>
          <el-button
              type="primary"
              @click="handleSubmitSetTime"
              size="small"
              class="dialog-btn dialog-btn-primary"
              :loading="submittingTime"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Registration">
import { listRegistration, getRegistration, delRegistration, addRegistration, updateRegistration } from "@/api/student/registration"
import { startImport, getImportProgress } from "@/api/student/registration.js"
// 修正：注册时间API路径（匹配SysRegistryTimeController）
import { getLatestRegistryTime, updateRegistryTime } from "@/api/student/registryTime.js"
import { selectStudentregistrationListByCollegeIds } from "@/api/student/allList.js"
import { getCurrentInstance, ref, reactive, toRefs, onMounted, onUnmounted } from 'vue'
import { Check, Close } from '@element-plus/icons-vue'
import {listYear} from "@/api/course/year.js"
const { proxy } = getCurrentInstance()
import {listTerm} from "@/api/course/term.js"
import {listCollege} from "@/api/college/college.js"
const collegeList = ref([])
// 学院ID -> 学院名称 的映射
const collegeMap = ref({})

// 专业ID -> 专业名称 的映射
const majorMap = {
  "010101": "马克思主义哲学",
  "010102": "中国哲学",
  "010105": "伦理学",
  "010107": "宗教学",
  "030105": "民商法学",
  "030201": "政治学理论",
  "030204": "中共党史",
  "030206": "国际政治",
  "030402": "马克思主义民族理论与政策",
  "030406": "中华民族学",
  "030407": "人类学与世界民族",
  "030501": "马克思主义基本原理",
  "030503": "马克思主义中国化研究",
  "030505": "思想政治教育",
  "030506": "中国近代史基本问题研究",
  "040101": "教育学原理",
  "040102": "课程与教学论",
  "040105": "学前教育",
  "040106": "高等教育",
  "040109": "特殊教育学",
  "040110": "教育技术学",
  "040201": "基础心理学",
  "040202": "发展与教育心理学",
  "040203": "应用心理学",
  "040301": "体育人文社会学",
  "040302": "运动人体科学",
  "040303": "体育教育训练学",
  "040304": "民族传统体育学",
  "045101": "教育管理",
  "045102": "学科教学（思政）",
  "045103": "学科教学（语文）",
  "045104": "学科教学（数学）",
  "045105": "学科教学（物理）",
  "045106": "学科教学（化学）",
  "045107": "学科教学（生物）",
  "045108": "学科教学（英语）",
  "045109": "学科教学（历史）",
  "045110": "学科教学（地理）",
  "045114": "现代教育技术",
  "045115": "小学教育",
  "045116": "心理健康教育",
  "045118": "学前教育",
  "045119": "特殊教育",
  "045201": "体育教学",
  "045202": "运动训练",
  "045204": "社会体育指导",
  "045300": "国际中文教育",
  "045400": "应用心理",
  "050101": "文艺学",
  "050102": "语言学及应用语言学",
  "050103": "汉语言文字学",
  "050104": "中国古典文献学",
  "050105": "中国古代文学",
  "050106": "中国现当代文学",
  "050107": "中国少数民族语言文学",
  "050211": "外国语言学及应用语言学",
  "055101": "英语笔译",
  "055102": "英语口译",
  "055103": "俄语笔译",
  "055104": "俄语口译",
  "060200": "中国史",
  "070101": "基础数学",
  "070102": "计算数学",
  "070104": "应用数学",
  "070201": "理论物理",
  "070205": "凝聚态物理",
  "070207": "光学",
  "070208": "无线电物理",
  "070301": "无机化学",
  "070302": "分析化学",
  "070303": "有机化学",
  "070304": "物理化学",
  "070501": "自然地理学",
  "070502": "人文地理学",
  "070503": "地图学与地理信息系统",
  "071000": "生物学",
  "083500": "软件工程",
  "085402": "通信工程（含宽带网络、移动通信等）",
  "085404": "计算机技术",
  "085600": "材料与化工",
  "085700": "资源与环境",
  "086000": "生物与医药",
  "125200": "公共管理",
  "125400": "旅游管理",
  "130100": "艺术学",
  "135200": "音乐",
  "135600": "美术与书法",
  "135700": "设计",
  "140300": "设计学",
  "145100": "文物",
  "020202": "区域经济学",
  "020205": "产业经济学",
  "020206": "国际贸易学",
  "025400": "国际商务",
  "035101": "法律（非法学）",
  "035102": "法律（法学）",
  "035200": "社会工作",
  "0401Z1": "少年儿童组织与思想意识教育"
};
const yearList = ref([])
const termList = ref([])
// 导入相关状态
const importProgressVisible = ref(false)
const importBatchNo = ref('')
const importProgress = ref(0)
const importStatus = ref('')
const importTotalCount = ref(0)
const importSuccessCount = ref(0)
const importErrorMsg = ref('')
const progressInterval = ref(null)

// 高级搜索相关状态
const showAdvancedSearch = ref(false)
const advancedSearchCollapse = ref([])

// 设置注册时间对话框相关状态
const setTimeDialogVisible = ref(false);
const setTimeForm = reactive({
  id: null, // 用于后端更新的主键ID
  startTime: null, // 注册开始时间
  endTime: null // 注册结束时间
});
const setTimeRules = reactive({
  startTime: [
    { required: true, message: "请选择注册开始时间", trigger: "change" },
    { type: "date", message: "开始时间格式不正确", trigger: "change" }
  ],
  endTime: [
    { required: true, message: "请选择注册结束时间", trigger: "change" },
    { type: "date", message: "结束时间格式不正确", trigger: "change" },
    // 自定义验证：结束时间必须大于开始时间
    {
      validator: (rule, value, callback) => {
        if (setTimeForm.startTime && value) {
          if (new Date(value) <= new Date(setTimeForm.startTime)) {
            callback(new Error("结束时间必须晚于开始时间"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ]
});
const loadingTime = ref(false); // 加载现有时间时的loading
const submittingTime = ref(false); // 提交更新时的loading

// 切换高级搜索显示/隐藏
const toggleAdvancedSearch = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value
  if (showAdvancedSearch.value) {
    advancedSearchCollapse.value = ['advanced']
  } else {
    advancedSearchCollapse.value = []
  }
}

const registrationList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: null,
    studentName: null,
    collegeId: null,
    collegeName: null,
    majorId: null,
    majorName: null,
    registrationSemester: null,
    registrationTime: null,
    registrationIp: null,
    browserInfo: null,
    osInfo: null,
    registrationStatus: null,
    auditUserId: null,
    auditTime: null,
    auditRemark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  },
  rules: {
    studentId: [
      { required: true, message: "学生学号不能为空", trigger: "blur" }
    ],
    studentName: [
      { required: true, message: "学生姓名不能为空", trigger: "blur" }
    ],
    registrationSemester: [
      { required: true, message: "注册学期不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询学生注册列表 */
function getList() {
  loading.value = true
  selectStudentregistrationListByCollegeIds(queryParams.value).then(response => {
    const rawRows = response.rows || [];
    // 处理数据：映射学院ID、学院名称、专业ID、专业名称
    registrationList.value = rawRows.map(row => {
      // 数据库中 collegeName 实际存的是「学院ID」，majorName 实际存的是「专业ID」
      const collegeId = row.collegeName;
      const majorId = row.majorName;
      return {
        ...row, // 保留原始所有字段
        collegeId: collegeId, // “学院ID”列显示 数据库中存的“学院ID”（即row.collegeName）
        collegeName: collegeMap[collegeId] || "未知学院", // “学院名称”列查映射
        majorId: majorId, // “专业ID”列显示 数据库中存的“专业ID”（即row.majorName）
        majorName: majorMap[majorId] || "未知专业" // “专业名称”列查映射
      };
    });
    total.value = response.total || 0
    loading.value = false
  }).catch(() => {
    loading.value = false
    registrationList.value = []
    total.value = 0
  })
}

function getTermList() {
  listTerm().then(response => {
    termList.value = response.rows || [];
  }).catch(() => {
    termList.value = [];
  });
}
//获取学院列表并转为map
function getCollegeList() {
  listCollege().then(response => {
    collegeList.value = response.rows || [];
    // 转换为学院ID -> 学院名称 的映射
    collegeMap.value = Object.fromEntries(collegeList.value.map(item => [item.collegeCode, item.collegeName]));
  }).catch(() => {
    collegeList.value = [];
  });
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    studentId: null,
    studentName: null,
    collegeId: null,
    collegeName: null,
    majorId: null,
    majorName: null,
    registrationSemester: null,
    registrationTime: null,
    registrationIp: null,
    browserInfo: null,
    osInfo: null,
    registrationStatus: null,
    auditUserId: null,
    auditTime: null,
    auditRemark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  }
  if (proxy.$refs["registrationRef"]) {
    proxy.$refs["registrationRef"].resetFields()
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  // 学院名称 → 学院ID 转换
  if (queryParams.value.collegeName) {
    // 从 collegeMap 中找到“名称对应的ID”
    const collegeId = Object.keys(collegeMap).find(key => collegeMap[key] === queryParams.value.collegeName);
    // 将转换后的ID赋值给查询参数
    queryParams.value.collegeName = collegeId || '';
  }

  // 专业名称 → 专业ID 转换
  if (queryParams.value.majorName) {z
    // 从 majorMap 中找到“名称对应的ID”
    const majorId = Object.keys(majorMap).find(key => majorMap[key] === queryParams.value.majorName);
    // 将转换后的ID赋值给查询参数
    queryParams.value.majorName = majorId || '';
  }

  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  if (proxy.$refs["queryRef"]) {
    proxy.$refs["queryRef"].resetFields()
  }
  // 手动清空转换相关的参数（避免残留ID）
  queryParams.value.collegeName = '';
  queryParams.value.majorName = '';
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = selection.length === 0
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加学生注册"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row ? row.id : ids.value[0]
  getRegistration(_id).then(response => {
    // 处理修改表单中的学院和专业信息
    const data = response.data;
    // 保留原始的ID值（数据库中存储的）
    const formData = {
      ...data,
      // 确保表单中显示正确的ID和名称
      collegeId: data.collegeName, // 学院ID使用数据库中存储的collegeName（实际是ID）
      collegeName: collegeMap[data.collegeName] || "未知学院", // 学院名称使用映射值
      majorId: data.majorName, // 专业ID使用数据库中存储的majorName（实际是ID）
      majorName: majorMap[data.majorName] || "未知专业" // 专业名称使用映射值
    };
    form.value = formData;
    open.value = true
    title.value = "修改学生注册"
  }).catch(error => {
    proxy.$modal.msgError(`获取数据失败: ${error.message || '未知错误'}`)
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["registrationRef"].validate(valid => {
    if (valid) {
      // 提交时需要将数据转换回数据库存储格式
      const submitData = {
        ...form.value,
        // 数据库中使用collegeName存储学院ID，majorName存储专业ID
        collegeName: form.value.collegeId,
        majorName: form.value.majorId,
        // 清除前端展示用的字段，避免提交到后端
        collegeId: null,
        majorId: null
      };

      if (form.value.id != null) {
        updateRegistration(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        }).catch(error => {
          proxy.$modal.msgError(`修改失败: ${error.message || '未知错误'}`)
        })
      } else {
        addRegistration(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        }).catch(error => {
          proxy.$modal.msgError(`新增失败: ${error.message || '未知错误'}`)
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row ? [row.id] : ids.value
  if (_ids.length === 0) {
    return proxy.$modal.msgWarning("请选择需要删除的数据")
  }

  proxy.$modal.confirm(`是否确认删除选中的${_ids.length}条数据？`).then(function() {
    return delRegistration(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('student/registration/export', {
    ...queryParams.value
  }, `registration_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
function handleImport() {
  proxy.$modal.confirm('确定要从学生基本信息导入注册数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    // 调用后端开始导入接口
    startImport().then(response => {
      if (response.code === 200) {
        importBatchNo.value = response.data
        importProgressVisible.value = true
        importStatus.value = '处理中'
        importProgress.value = 0
        // 开始轮询进度
        startProgressPolling()
      } else {
        proxy.$modal.msgError(response.msg || '导入任务启动失败')
      }
    }).catch(error => {
      proxy.$modal.msgError('导入任务启动失败：' + (error.msg || error.message))
    })
  })
}

/** 开始轮询进度 */
function startProgressPolling() {
  // 清除可能存在的旧定时器
  if (progressInterval.value) {
    clearInterval(progressInterval.value)
  }

  // 立即查询一次
  queryImportProgress()

  // 设置定时器，每3秒查询一次进度
  progressInterval.value = setInterval(() => {
    queryImportProgress()
  }, 3000)
}

/** 查询导入进度 */
function queryImportProgress() {
  getImportProgress(importBatchNo.value).then(response => {
    if (response.code === 200) {
      const progressData = response.data
      importProgress.value = progressData.progress || 0
      importStatus.value = progressData.status || '处理中'
      importTotalCount.value = progressData.total || 0
      importSuccessCount.value = progressData.successCount || 0
      importErrorMsg.value = progressData.errorMsg || ''
      // 如果任务已完成或失败，停止轮询
      if (importStatus.value === '完成' || importStatus.value === '失败') {
        clearInterval(progressInterval.value)
        progressInterval.value = null

        // 如果导入成功，刷新列表
        if (importStatus.value === '完成') {
          setTimeout(() => {
            getList()
          }, 1000)
        }
      }
    } else {
      proxy.$modal.msgWarning('获取导入进度失败：' + response.msg)
      clearInterval(progressInterval.value)
      progressInterval.value = null
    }
  }).catch(error => {
    console.error('查询导入进度失败', error)
    clearInterval(progressInterval.value)
    progressInterval.value = null
  })
}

/** 关闭导入进度对话框 */
function closeImportProgress() {
  importProgressVisible.value = false
  if (progressInterval.value) {
    clearInterval(progressInterval.value)
    progressInterval.value = null
  }
}

/** 取消导入 */
function cancelImport() {
  proxy.$modal.confirm('确定要取消当前导入任务吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里可以调用后端取消接口，如果有的话
    closeImportProgress()
    proxy.$modal.msgInfo('已取消导入任务')
  })
}

// 打开“设置注册时间”对话框（加载现有时间）
function handleOpenSetTimeDialog() {
  setTimeDialogVisible.value = true;
  loadingTime.value = true;

  // 调用后端接口，获取最新的注册时间配置（回显数据）
  getLatestRegistryTime().then(response => {
    const latestTime = response.data || {};
    setTimeForm.id = latestTime.id; // 保存主键ID（用于后续更新）
    setTimeForm.startTime = latestTime.startTime || null; // 回显开始时间
    setTimeForm.endTime = latestTime.endTime || null; // 回显结束时间
  }).catch(error => {
    proxy.$modal.msgError(`获取现有时间失败：${error.message || '未知错误'}`);
    setTimeDialogVisible.value = false;
  }).finally(() => {
    loadingTime.value = false;
  });
}

// 提交更新注册时间
function handleSubmitSetTime() {
  proxy.$refs["setTimeFormRef"].validate(valid => {
    if (valid) {
      submittingTime.value = true;

      // 调用后端更新接口（携带主键ID，确保更新正确的记录）
      updateRegistryTime(setTimeForm).then(response => {
        if (response.code === 200) {
          proxy.$modal.msgSuccess("注册时间设置成功！");
          setTimeDialogVisible.value = false;
        } else {
          proxy.$modal.msgError(response.msg || "设置失败");
        }
      }).catch(error => {
        proxy.$modal.msgError(`设置失败：${error.message || '未知错误'}`);
      }).finally(() => {
        submittingTime.value = false;
      });
    }
  });
}

// 组件卸载时清除定时器
onUnmounted(() => {
  if (progressInterval.value) {
    clearInterval(progressInterval.value)
  }
})

// 初始化加载数据
onMounted(() => {
  getCollegeList()
  getTermList()
  getList()
})
</script>

<style scoped>
/* 基础样式与工具类 */
.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.align-center {
  align-items: center;
}

.mb-2 {
  margin-bottom: 8px;
}

.mb-3 {
  margin-bottom: 12px;
}

.mb-4 {
  margin-bottom: 16px;
}

.ml-auto {
  margin-left: auto;
}

.mr-2 {
  margin-right: 8px;
}

.text-lg {
  font-size: 16px;
}

.font-semibold {
  font-weight: 500;
}

.text-primary {
  color: #409eff;
}

.text-gray-500 {
  color: #606266;
}

.font-medium {
  font-weight: 500;
}

.mt-4 {
  margin-top: 16px;
}

/* 搜索区域样式 */
.search-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.search-header {
  padding: 0 15px;
}

.search-toggle-btn {
  color: #409eff;
  transition: color 0.2s;
}

.search-toggle-btn:hover {
  color: #66b1ff;
}

/* 表单元素样式 */
.form-input {
  transition: border-color 0.2s, box-shadow 0.2s;
}

.form-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.form-select {
  transition: border-color 0.2s, box-shadow 0.2s;
}

.form-select:focus-within {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.form-textarea {
  resize: vertical;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.form-textarea:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 操作按钮区域 */
.operation-bar {
  padding: 8px 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.operation-btn {
  transition: all 0.2s;
  border-radius: 4px;
}

.operation-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

/* 表格区域样式 */
.table-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.table-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.table-header {
  padding: 0 15px;
}

.content-table {
  border-radius: 6px;
  transition: all 0.2s;
}

.content-table .el-table__row {
  transition: background-color 0.2s;
}

.content-table .el-table__row:hover {
  background-color: #f9fafc;
}

.table-operation-btn {
  transition: color 0.2s;
  margin: 0 3px;
}

.table-operation-btn:hover {
  transform: translateY(-1px);
}

/* 分页样式 */
.pagination {
  text-align: right;
}

/* 对话框样式 */
.custom-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.dialog-form {
  margin-top: 10px;
}

.custom-dialog .el-dialog__header {
  background-color: #f5f7fa;
  padding: 12px 20px;
  border-bottom: 1px solid #eee;
}

.custom-dialog .el-dialog__title {
  font-size: 16px;
  font-weight: 500;
}

.custom-dialog .el-dialog__footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.dialog-btn {
  transition: all 0.2s;
  border-radius: 4px;
}

.dialog-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.dialog-btn-primary {
  background-color: #409eff;
  border-color: #409eff;
}

.dialog-btn-primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 状态标签样式 */
::v-deep .el-tag {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  transition: all 0.2s;
}

::v-deep .el-tag:hover {
  transform: scale(1.05);
}

/* 加载动画优化 */
::v-deep .el-loading-spinner {
  top: 50%;
  transform: translateY(-50%);
}

::v-deep .el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
}

/* 导入进度对话框样式 */
.import-progress-container {
  padding: 10px 0;
}

.status-info {
  padding: 15px 0;
}

.success-state {
  color: #67c23a;
}

.error-state {
  color: #f56c6c;
}

.success-icon {
  font-size: 48px;
  color: #67c23a;
}

.error-icon {
  font-size: 48px;
  color: #f56c6c;
}

.error-message {
  color: #f56c6c;
  max-width: 300px;
  margin: 10px auto;
  word-break: break-word;
}

.progress-stats {
  color: #606266;
}

.operation-bar-flex {
  display: flex;
  flex-wrap: wrap; /* 屏幕缩小时自动换行 */
  gap: 8px; /* 按钮之间的间距 */
  padding: 8px 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  align-items: center;
}

.operation-btn {
  min-width: 100px; /* 每个按钮的最小宽度，避免内容挤压 */
}
</style>
